// response.interceptor.ts
import {
    Injectable,
    NestInterceptor,
    ExecutionContext,
    CallHandler,
  } from '@nestjs/common';
  import { Observable } from 'rxjs';
  import { map, catchError } from 'rxjs/operators';
  
  interface ApiResponse<T> {
    code: number;
    msg: string;  // 将 message 简写为 msg
    data?: T;
  }
  
  @Injectable()
  export class ResponseInterceptor<T> implements NestInterceptor<T, ApiResponse<T>> {
    intercept(context: ExecutionContext, next: CallHandler): Observable<ApiResponse<T>> {
      return next.handle().pipe(
        map(data => ({
          code: 0,
          msg: '请求成功',  // 更新为 msg
          data,
        })),
        catchError(err => {
          const response = context.switchToHttp().getResponse();
          const statusCode = response.statusCode;
  
          let code = 1;
          let msg = '请求失败';  // 更新为 msg
  
          if (statusCode >= 500) {
            code = 3;
            msg = '服务器错误';  // 更新为 msg
          } else {
            msg = err.message || msg;
          }
  
          return [{ code, msg }];  // 更新为 msg
        }),
      );
    }
  }
  